<?php
/**
 * hyperf-skeleton
 * Create on  2021/1/25 11:41
 * Create by tangzq
 */

namespace App\Jwt;


use Firebase\JWT\JWT;

class SelfJwt
{
    /**
     * @return array|bool|mixed|string|void
     * @throws \Exception
     */
    private static function getKey()
    {
        $jwtKey  =  env('JWT_KEY','');
        if($jwtKey) {
            return $jwtKey;
        }

        throw new \Exception('获取 JWT_KEY 失败');
    }

    private static function getPayload(array $externalData = [])
    {
        $time = time();
        $default =
            [
                "iat" => $time,
                "nbf" => $time,
                "exp" => $time + 3600];

        if (!empty($externalData)) {
            $default = array_merge($externalData, $default);
        }

        return $default;
    }

    public static function encode(array $externalData = [])
    {
        return JWT::encode(self::getPayload($externalData), self::getKey());
    }

    public static function decode(string $jwt)
    {
        return (array)(JWT::decode($jwt, self::getKey(), ['HS256']));
    }

    public static function getUserData(string $jwt)
    {
        $user = (self::decode($jwt))['user'] ?? '';
        $user = json_decode($user, true);
        if (!isset($user['UserId'], $user['IsAdmin'])) {
            return null;
        }

        return $user;
    }
}